package com.osi.mes.qm.services;

import java.util.HashSet;
import java.util.List;
import java.util.Vector;

import pnuts.lang.Context;

import com.datasweep.compatibility.client.ATHandler;
import com.datasweep.compatibility.client.ATRow;
import com.datasweep.compatibility.client.ATRowFilter;
import com.datasweep.compatibility.client.DatasweepException;
import com.datasweep.compatibility.client.DsList;
import com.datasweep.compatibility.client.Response;
import com.datasweep.compatibility.pnuts.Functions;
import com.datasweep.compatibility.ui.Time;
import com.osi.mes.base.BaseService;
import com.osi.mes.excel.ExcelPoiParser;
import com.osi.mes.qm.base.constants.IATNames;
import com.osi.mes.qm.base.constants.IBasicConstants;
import com.osi.mes.qm.qtyEqu.bean.QtyEquipment;
import com.osi.mes.utils.StringUtils;

public class QmEquService extends BaseService implements IATNames
{
	public QmEquService(Functions functions)
	{
		super(functions);
	}

	public QmEquService(Context context)
	{
		super(context);
	}

	public int saveEquDateFromExcel(String excelFilePath, int ingnoreTopRows,
		int ingnoreBottomRowNumber, String dateFormatter)
		throws Exception
	{
		int referenceCount = 0;

		ExcelPoiParser.ingnoreTopRowNumber = ingnoreTopRows;
		ExcelPoiParser.ingnoreBottomRowNumber = ingnoreBottomRowNumber;
		ExcelPoiParser.DATE_FORMAT1 = dateFormatter;

		List qtyEqus = ExcelPoiParser.parseExcelFile(
			excelFilePath, "com.osi.mes.qm.qtyEqu.bean.QtyEquipment");
		System.out.println("res: " + qtyEqus.size());
		if (qtyEqus == null || qtyEqus.size() == 0)
			return referenceCount;

		ATHandler atHandler = getFunctions().createATHandler(
			IATNames.AT_EQU_QTY_REC);
		for (int i = 0; i < qtyEqus.size(); i++)
		{
			Object obj = qtyEqus.get(i);
			if (obj instanceof QtyEquipment)
			{
				QtyEquipment qtyEqu = (QtyEquipment) obj;

				ATRow oldAtRow = getEquByAssetNo(qtyEqu.getShip_cop_no());
				ATRow atRow = null;
				if (oldAtRow != null)
					atRow = oldAtRow;
				else
					atRow = atHandler.createATRow();

				atRow.setName(qtyEqu.getShip_cop_no());
				atRow.setValue(
					IATNames.AT_USING_PLACE, qtyEqu.getUsing_place());
				atRow.setValue(
					IATNames.AT_EQU_NAME, qtyEqu.getEqu_name());
				atRow.setValue(
					IATNames.AT_EQU_MODEL, qtyEqu.getEqu_model());
				atRow.setValue(
					IATNames.AT_SHIP_NO, qtyEqu.getShip_no());
				atRow.setValue(
					IATNames.AT_SHIP_COP_NAME, qtyEqu.getShip_cop_name());
				atRow.setValue(
					IATNames.AT_SHIP_DATE, qtyEqu.getShip_date());

				atRow.setValue(
					IATNames.AT_PURCHASE_TIME, qtyEqu.getPurchase_time());
				atRow.setValue(
					IATNames.AT_MEASURE_RANGE, qtyEqu.getMeasure_range());
				atRow.setValue(
					IATNames.AT_VERIFICATION_SCALE, qtyEqu.getVerification_scale());
				atRow.setValue(
					IATNames.AT_SHIP_COP_NO, qtyEqu.getShip_cop_no());
				atRow.setValue(
					IATNames.AT_USING_PEOPLE, qtyEqu.getUsing_people());

				if (qtyEqu.getDetect_frequence() != null)
					atRow.setValue(
						IATNames.AT_DETECT_FREQUENCY, new Long(qtyEqu.getDetect_frequence()));

				atRow.setValue(
					IATNames.AT_VERIFICATION_DATE, qtyEqu.getVerification_date());
				atRow.setValue(
					IATNames.AT_EXPIRATION_DATE, qtyEqu.getExpiration_date());

				int cerType = getValueFromList(
					qtyEqu.getCertificate_type(), IBasicConstants.QTY_REC_EQU_TYPE_LIST_NAME,
					IBasicConstants.QTY_REC_MSG_NAME);
				if (cerType > -1)
					atRow.setValue(
						IATNames.AT_CERTIFICATE_TYPE, cerType);

				atRow.setValue(
					IATNames.AT_CERTIFICATE_NO, qtyEqu.getCertificate_no());
				atRow.setValue(
					IATNames.AT_EACH_PRICE, new Float(qtyEqu.getEquPrice()));
				atRow.setValue(
					IATNames.AT_VENDER_TEL, qtyEqu.getVendor_tel());

				atRow.setValue(
					IATNames.AT_CONTACT_PEOPLE, qtyEqu.getContact_people());
				atRow.setValue(
					IATNames.AT_CONTACT_MAIL, qtyEqu.getContact_mail());
				atRow.setValue(
					IATNames.AT_FIXED_ASSET_NO, qtyEqu.getFixed_asset_no());

				int equType = getValueFromList(
					qtyEqu.getEqu_type(), IBasicConstants.QTY_REC_EQU_TYPE_LIST_NAME,
					IBasicConstants.QTY_REC_MSG_NAME);
				if (equType > -1)
					atRow.setValue(
						IATNames.AT_EQU_TYPE, equType);

				atRow.setValue(
					IATNames.AT_MARK, qtyEqu.getMark());

				int equState = getValueFromList(
					qtyEqu.getEqu_state(), IBasicConstants.QTY_REC_EQU_STATE_LIST_NAME,
					IBasicConstants.QTY_REC_MSG_NAME);
				if (equState > -1)
					atRow.setValue(
						IATNames.AT_EQU_STATE, equState);

				Response response = atRow.save(
					getTrxTime(), null, null);
				if (response.isOk())
					referenceCount++;
				else
					throw new Exception("Save ATRow Fail： " + response.getFirstErrorMessage());
			}
		}

		return referenceCount;
	}

	private int getValueFromList(String value, String listName, String msgName)
	{
		if (value == null || "null".equals(value))
			return -1;

		DsList cusCompTypes = getFunctions().getList(
			listName);
		if (cusCompTypes == null)
			return -1;

		List cusList = cusCompTypes.getItems();
		if (cusList == null || cusList.size() == 0)
			return -1;

		for (int i = 0; i < cusList.size(); i++)
		{
			String cus = (String) cusList.get(i);
			String val = getFunctions().getMessage(
				msgName, cus);
			if (value.equals(val))
				return i;
		}

		return -1;
	}

	// 获得需要检定的质量设备
	public Vector getNeedChkEquList()
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_QTY_REC;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		rowFilter.forColumnNameNotEqualTo(
			IATNames.AT_EQU_STATE, IBasicConstants.SCRAPPED_EQU);
		return atHandler.getATRowsByFilter(
			rowFilter, false);
	}

	// 获得需要做校准的质量设备 停用，报废的设备都不需要做
	public Vector getNeedAdEquList()
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_QTY_REC;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		rowFilter.forColumnNameEqualTo(
			IATNames.AT_EQU_STATE, IBasicConstants.NORMAL_EQU);
		return atHandler.getATRowsByFilter(
			rowFilter, false);
	}

	// 通过名称获得质量设备
	public ATRow getEqu(String equName)
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_QTY_REC;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		rowFilter.forColumnNameEqualTo(
			IATNames.AT_EQU_NAME, equName);
		Vector matchedEqus = atHandler.getATRowsByFilter(
			rowFilter, false);

		if (matchedEqus == null || matchedEqus.size() == 0)
			return null;

		return (ATRow) matchedEqus.get(0);
	}

	// 获得设备，通过cop no
	public ATRow getEquByAssetNo(String fixedAssetNo)
		throws DatasweepException
	{
		if (StringUtils.isNull(fixedAssetNo))
			return null;

		String atDefName = IATNames.AT_EQU_QTY_REC;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		rowFilter.forColumnNameEqualTo(
			IATNames.AT_SHIP_COP_NO, fixedAssetNo);
		Vector matchedEqus = atHandler.getATRowsByFilter(
			rowFilter, false);

		if (matchedEqus == null || matchedEqus.size() == 0)
			return null;

		return (ATRow) matchedEqus.get(0);
	}

	// 获得未停用的设备
	public Vector getNotDisabledEqus()
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_QTY_REC;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		rowFilter.forColumnNameEqualTo(
			IATNames.AT_EQU_STATE, IBasicConstants.NORMAL_EQU);
		Vector<ATRow> matchedEqus = atHandler.getATRowsByFilter(
			rowFilter, false);

		return makeNames(matchedEqus);
	}

	public Vector getNotScrappedEqus()
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_QTY_REC;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		rowFilter.forColumnNameNotEqualTo(
			IATNames.AT_EQU_STATE, IBasicConstants.SCRAPPED_EQU);
		Vector matchedEqus = atHandler.getATRowsByFilter(
			rowFilter, false);

		return makeNames(matchedEqus);
	}

	private Vector<String> makeNames(Vector<ATRow> equAts)
	{
		Vector<String> vec = new Vector<String>();
		if (equAts == null || equAts.size() == 0)
			return vec;

		for (int i = 0; i < equAts.size(); i++)
		{
			ATRow atRow = equAts.get(i);
			if (atRow != null)
			{
				Object equCode = atRow.getValue(IATNames.AT_SHIP_COP_NO);
				if (equCode != null)
					vec.add(equCode.toString());
			}
		}

		return vec;
	}

	// 查询温度计校准记录
	public Vector<ATRow> getTherAdResults(String equCode, Time chkTimeFrom, Time chkTimeTo,
		int auditState)
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_THERMOMETER_AD;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		if (!StringUtils.isNull(equCode))
		{
			rowFilter.forColumnNameEqualTo(
				AT_EQU_THE_EQU_CODE, equCode);
		}
		if (chkTimeFrom != null)
		{
			chkTimeFrom = super.getDayStart(chkTimeFrom);
			rowFilter.forColumnNameGreaterThanOrEqualTo(
				AT_EQU_THE_AD_TIME, chkTimeFrom);
		}
		if (chkTimeTo != null)
		{
			chkTimeTo = super.getDayEnd(chkTimeTo);
			rowFilter.forColumnNameLessThan(
				AT_EQU_THE_AD_TIME, chkTimeTo);
		}

		if (auditState > -1)
			rowFilter.forColumnNameEqualTo(
				AT_EQU_THE_AUDIT_STATE, auditState == 0);

		return atHandler.getATRowsByFilter(
			rowFilter, false);
	}

	// 查询计时设备校准记录
	public Vector<ATRow> getEquInsAdResults(String equCode, Time chkTimeFrom, Time chkTimeTo,
		int auditState)
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_INSTANT_AD;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		if (!StringUtils.isNull(equCode))
		{
			rowFilter.forColumnNameEqualTo(
				AT_EQU_INSTANT_EQU_CODE, equCode);
		}
		if (chkTimeFrom != null)
		{
			chkTimeFrom = super.getDayStart(chkTimeFrom);
			rowFilter.forColumnNameGreaterThanOrEqualTo(
				AT_EQU_INSTANT_AD_TIME, chkTimeFrom);
		}
		if (chkTimeTo != null)
		{
			chkTimeTo = super.getDayEnd(chkTimeTo);
			rowFilter.forColumnNameLessThan(
				AT_EQU_INSTANT_AD_TIME, chkTimeTo);
		}

		if (auditState > -1)
			rowFilter.forColumnNameEqualTo(
				AT_EQU_INSTANT_AUDIT_STATE, auditState == 0);

		return atHandler.getATRowsByFilter(
			rowFilter, false);
	}

	// 查询温度计电子秤校准记录
	public Vector<ATRow> getEleBalanceAdResults(String equCode, Time chkTimeFrom, Time chkTimeTo,
		int auditState)
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_ELE_BALANCE_AD;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);
		if (!StringUtils.isNull(equCode))
		{
			rowFilter.forColumnNameEqualTo(
				AT_EQU_ELE_BALANCE_EQU_CODE, equCode);
		}

		if (chkTimeFrom != null)
		{
			chkTimeFrom = super.getDayStart(chkTimeFrom);
			rowFilter.forColumnNameGreaterThanOrEqualTo(
				AT_EQU_ELE_BALANCE_AD_TIME, chkTimeFrom);
		}
		if (chkTimeTo != null)
		{
			chkTimeTo = super.getDayEnd(chkTimeTo);
			rowFilter.forColumnNameLessThan(
				AT_EQU_ELE_BALANCE_AD_TIME, chkTimeTo);
		}
		if (auditState > -1)
			rowFilter.forColumnNameEqualTo(
				AT_EQU_ELE_BALANCE_AUDIT_STATE, auditState == 0);

		return atHandler.getATRowsByFilter(
			rowFilter, false);
	}

	// 查询设备
	public Vector<ATRow> getEqus(String equNo, String equName, Time nextChkTime, int equType,
		int equState)
		throws DatasweepException
	{
		HashSet<ATRow> atRows = new HashSet<ATRow>();
		Vector<ATRow> expirationEqus = getExpirationEqus(
			equNo, equName, nextChkTime, equType, equState);
		Vector<ATRow> warnEqus = getWarnEqus(
			equNo, equName, nextChkTime, equType, equState);
		expirationEqus.addAll(warnEqus);
		atRows.addAll(expirationEqus);
		atRows.addAll(warnEqus);

		Vector<ATRow> vec = new Vector<ATRow>();
		vec.addAll(atRows);
		return vec;
	}

	public Vector<ATRow> getExpirationEqus(String equNo, String equName, Time nextChkTime,
		int equType, int equState)
		throws DatasweepException
	{
		String atDefName = IATNames.AT_EQU_QTY_REC;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);

		if (!StringUtils.isNull(equNo))
		{
			rowFilter.forColumnNameContaining(
				AT_SHIP_COP_NO, equNo);
		}
		if (!StringUtils.isNull(equName))
		{
			rowFilter.forColumnNameContaining(
				AT_EQU_NAME, equName);
		}

		if (nextChkTime != null)
		{
			rowFilter.forColumnNameLessThan(
				AT_EXPIRATION_DATE, getDayEnd(nextChkTime));
		}

		if (equType > -1)
			rowFilter.forColumnNameEqualTo(
				AT_EQU_TYPE, equType);

		if (equState > -1)
			rowFilter.forColumnNameEqualTo(
				AT_EQU_STATE, equState);

		Vector expirationEqus = atHandler.getATRowsByFilter(
			rowFilter, false);
		if (expirationEqus == null)
			new Vector();

		return expirationEqus;
	}

	public Vector<ATRow> getWarnEqus(String equNo, String equName, Time nextChkTime, int equType,
		int equState)
		throws DatasweepException
	{
		Vector<ATRow> atRows = new Vector<ATRow>();
		String atDefName = IATNames.AT_EQU_QTY_REC;
		ATHandler atHandler = getFunctions().createATHandler(
			atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(
			atDefName);

		if (!StringUtils.isNull(equNo))
		{
			rowFilter.forColumnNameContaining(
				AT_SHIP_COP_NO, equNo);
		}

		if (!StringUtils.isNull(equName))
		{
			rowFilter.forColumnNameContaining(
				AT_EQU_NAME, equName);
		}

		if (nextChkTime != null)
		{
			rowFilter.forColumnNameGreaterThan(
				AT_EXPIRATION_DATE, getDayStart(nextChkTime));
		}

		if (equType > -1)
			rowFilter.forColumnNameEqualTo(
				AT_EQU_TYPE, equType);

		if (equState > -1)
			rowFilter.forColumnNameEqualTo(
				AT_EQU_STATE, equState);

		Vector warnEqus = atHandler.getATRowsByFilter(
			rowFilter, false);

		if (nextChkTime == null)
			return warnEqus;

		for (int i = 0; i < warnEqus.size(); i++)
		{
			ATRow equATRow = (ATRow) warnEqus.get(i);
			Object remindCycleObj = equATRow.getValue(AT_EQU_CHK_REMIND_CYCLE);
			Long remindCycle = null;
			if (remindCycleObj instanceof Long)
			{
				remindCycle = (Long) remindCycleObj;
			}

			Time chkTime = null;
			if (equATRow.getValue(IATNames.AT_EXPIRATION_DATE) instanceof Time)
			{
				chkTime = (Time) equATRow.getValue(IATNames.AT_EXPIRATION_DATE);
			}

			if (chkTime != null && remindCycle != null)
			{
				int cycle = remindCycle.intValue();
				cycle = 0 - cycle;
				chkTime = chkTime.addDays(cycle);
			}

			if (chkTime.compareTo(nextChkTime) < 0)
			{
				atRows.add(equATRow);
			}
		}

		return atRows;
	}
}
